package edu.chinasoft.servlet;

import edu.chinasoft.domain.User;
import edu.chinasoft.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "myuserRegisterServlet",value = "/servlet/userregisterservlet")
public class UserRegisterServlet extends HttpServlet {
    private UserService userService;
    private static Logger logger = LoggerFactory.getLogger(UserRegisterServlet.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info(" UserRegisterServlet >doPost start.......");
        String userName = request.getParameter("username");
        String userPassword = request.getParameter("userpassword");
        User user = new User();
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        System.out.println(user);
        //获取spring框架的配置文件创建的服务层对象
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        UserService userServiceImp = wac.getBean("userService",UserService.class);
        userService = userServiceImp;
        System.out.println("获取bean对象结束！");

        List<User> userList = userService.selectUserByUserName(user);
        if (userList.size()==0){//用户不存在，可以注册
            userService.insertUser(user);
            System.out.println("注册用户结束！");
            response.sendRedirect(request.getContextPath()+"/userRegisterSuccess.jsp");
        }else{//用户已存在，不能注册
            response.sendRedirect(request.getContextPath()+"/userRegisterError.jsp");
        }

        logger.info(" UserRegisterServlet >doPost end.......");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info(" UserRegisterServlet >doGet start.......");

        logger.info(" UserRegisterServlet >doGet end.......");
    }
}
